
#include <iostream>
#include <string>
#include <vector>
#include <poll.h>
#include <sys/time.h>
#include "Log.hpp"
#include "Sock.hpp"

#define FD_NONE -1

using namespace std;

class PollServer
{
private:
    uint16_t _port;
    int _listensock;
    struct pollfd *_fds;
    int _nfds;
    int _timeout;

private:
    void HandlerEvent()
    {
        for (int i = 0; i < _nfds; i++)
        {
            if (_fds[i].fd == FD_NONE)
                continue;
            if (_fds[i].revents & POLLIN)
            {
                // 读就绪的时候，将sock加入“列表”中
                if (_fds[i].fd == _listensock)
                    Accepter();
                else
                    Recver(i);
            }
        }
    }

    void Accepter()
    {
        string clientip;
        uint16_t clientport = 0;

        int sock = Sock::Accept(_listensock, &clientip, &clientport);
        if (sock < 0)
        {
            logMessage(WARNING, "accept error");
            return;
        }
        logMessage(DEBUG, "get a new line success:%d", sock);
        int pos = 1;
        for (; pos < _nfds; pos++)
        {
            if (_fds[pos].fd == FD_NONE)
                break;
        }
        if (pos == _nfds)
        {
            logMessage(WARNING, "%s:%d", "poll server already full , close :%d", sock);
            close(sock);
        }
        else
        {
            // 将获取的连接加入到Poll中
            _fds[pos].fd = sock;
            _fds[pos].events = POLLIN;
        }
    }

    void Recver(int pos)
    {
        logMessage(DEBUG, "messge in , get io event %d", _fds[pos]);
        char buffer[1024];
        int n = recv(_fds[pos].fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            logMessage(DEBUG, "client[%d]:%s", _fds[pos].fd, buffer);
        }
        else if (n == 0)
        {
            logMessage(DEBUG, "client[%d] quit,me too...", _fds[pos].fd);
            close(_fds[pos].fd);
            _fds[pos].fd = FD_NONE;
            _fds[pos].events = 0;
        }
        else
        {
            logMessage(DEBUG, "%d sock recv error ,%d:%s", _fds[pos].fd, errno, strerror(errno));
            close(_fds[pos].fd);
            _fds[pos].fd = FD_NONE;
            _fds[pos].events = 0;
        }
    }

    void DebugPrint()
    {
        cout << "_fd_array[]: ";
        for (int i = 0; i < _nfds; i++)
        {
            if (_fds[i].fd == FD_NONE)
                continue;
            cout << _fds[i].fd << " ";
        }
        cout << endl;
    }

public:
    static const int nfds = 100;
    PollServer(const uint16_t &port = 8080) : _port(port), _nfds(nfds)
    {
        _listensock = Sock::Socket();
        Sock::Bind(_listensock, _port);
        Sock::Listen(_listensock);
        logMessage(DEBUG, "%s", "mag create base socket success!");

        _fds = new struct pollfd[_nfds];
        for (int i = 0; i < _nfds; i++)
        {
            _fds[i].fd = FD_NONE;
            _fds[i].events = _fds[i].revents = 0;
        }
        _fds[0].fd = _listensock;
        _fds[0].events = POLLIN;

        _timeout = 1000;
    }
    ~PollServer()
    {
        if (_listensock >= 0)
        {
            close(_listensock);
        }
        if (_fds)
            delete[] _fds;
    }

    void Start()
    {
        while (true)
        {
            int n = poll(_fds, _nfds, _timeout);
            switch (n)
            {
            case 0:
                logMessage(DEBUG, "%s", "time out");
                break;
            case -1:
                logMessage(WARNING, "%d:%s", errno, strerror(errno));
                break;
            default:
                HandlerEvent();
                break;
            }
        }
    }
};
